package src;

import java.io.IOException;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.FileReader;

public class ConnectionManager implements Runnable
{
    private String[] bannedHosts;
    private boolean running = true;

    public ConnectionManager()
    {
    }

    public void run()
    {
        loadBannedHosts("BANNEDHOSTS.DAT");
        Socket s = null;
        String hostAddress = "";
        int connectionType = 0;
        while(running)
        {
            try
            {
                s = Main.m.socket.accept();
                s.setTcpNoDelay(true);
                hostAddress = s.getInetAddress().getHostAddress();
                if(s != null && hostAddress != null)
                {
                    connectionType = s.getInputStream().read();
                    if((connectionType & 0xFF) == 14)
                    {
                        if(checkBanned(hostAddress))
                        {
                            Main.m.log("Banned client connecting from " + hostAddress);
                        }
                        Main.m.log("Client successfully connecting from " + hostAddress);
                        Main.m.ge.newPlayer(s, hostAddress);
                        s = null;
                    }
                }
            }
            catch(Exception e)
            {
                s = null;
            }
            try
            {
                Thread.sleep(100);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
        Main.m.log("Connection manager unexpectedly ended.");
    }

    public boolean checkBanned(String hostName)
    {
        if(hostName == null)
        {
            return true;
        }
        for(int i = 0; i < bannedHosts.length; i++)
        {
            if(bannedHosts[i] != null && (hostName.startsWith(bannedHosts[i]) || hostName.equals(bannedHosts[i])))
            {
                return true;
            }
        }
        return false;
    }

    private void loadBannedHosts(String file)
    {
        bannedHosts = new String[25];
        int index = 0;
        try
        {
            BufferedReader in = new BufferedReader(new FileReader("./src/Data/DAT/" + file));
            String loggedIPs = null;
            while ((loggedIPs = in.readLine()) != null)
            {
                bannedHosts[index] = loggedIPs;
                index++;
            }
        }
        catch(IOException ioe)
        {
            Main.m.log("Error loading banned hosts list.");
        }
    }
}